#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include "macaddr.h"

#define MAX_IFNAME_LEN 256

// 读取指定网卡的MAC地址
int read_macaddr(const char *ifname, char macaddr[MACADDR_LEN]) {
    char path[MAX_IFNAME_LEN + 20];
    FILE *fp;
    
    snprintf(path, sizeof(path), "/sys/class/net/%s/address", ifname);
    
    fp = fopen(path, "r");
    if (!fp) {
        perror(path);
        return -1;
    }
    
    if (fgets(macaddr, MACADDR_LEN, fp) == NULL) {
        fclose(fp);
        return -1;
    }
    
    // 去除可能的换行符
    macaddr[strcspn(macaddr, "\n")] = '\0';
    fclose(fp);
    return 0;
}

// 遍历所有网络接口并打印MAC地址
int get_macaddr(char macaddr[MACADDR_LEN])
{
    DIR *dir;
    struct dirent *entry;
    int retval = -1;
    
    dir = opendir("/sys/class/net");
    if (!dir) {
        perror("/sys/class/net");
        return -1;
    }

    while ((entry = readdir(dir)) != NULL) {
        // 跳过"."和".."目录项
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }
        
        // 跳过无效接口
        if (strcmp(entry->d_name, "lo") == 0) {
            continue;
        }
        
        if (read_macaddr(entry->d_name, macaddr) == 0) {
            //只读取第一个网卡的地址
            retval = 0;
            break;
        }
    }
    
    closedir(dir);
    return retval;
}
